package com.hp.attendance.serlvet.leave;

import com.hp.attendance.entity.dto.LeaveEmpDto;
import com.hp.attendance.entity.Employee;
import com.hp.attendance.entity.Leave;
import com.hp.attendance.service.EmployeeService;
import com.hp.attendance.service.LeaveService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/leaveList")
public class LeaveListServlet extends HttpServlet {
    private LeaveService leaveService = new LeaveService();
    private EmployeeService employeeService = new EmployeeService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查询请假记录
        try {
            //查询Leave的所有请假记录
            List<Leave> leaveByNumbers = leaveService.getList();
            //获取employee的所有员工
            List<Employee> list = employeeService.getList();
            //创建一个Dto泛型的list的集合
            ArrayList<LeaveEmpDto> leaveEmpDto = new ArrayList<LeaveEmpDto>();
            //遍历每一个员工  拿出每个员工信息对象
            for (Employee employee : list) {
                //遍历所有的请假记录
                for (Leave leaveByNumber : leaveByNumbers) {
                    //判断编号: 当员工表编号和请假表编号相同时
                    if (leaveByNumber.getEmployee_number().equals(employee.getEmployee_number())) {
                        //创建一个Dto对象
                        LeaveEmpDto leaveEmpDto1 = new LeaveEmpDto();
                        //将请假表的员工编号存入Dto对象中
                        leaveEmpDto1.setLeave(leaveByNumber);
                        //将员工表的员工编号存入Dto对象中
                        leaveEmpDto1.setName(employee.getName());
                        //Dto对象存入list的集合中
                        leaveEmpDto.add(leaveEmpDto1);
                    }
                }
            }
            //设置到前端界面中
            req.setAttribute("list", leaveEmpDto);
            req.getRequestDispatcher("pages/leave_list.jsp").forward(req, resp);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
